class MQuery {
    constructor(selector) {
        if (typeof selector === 'string') {
            this.elements = Array.from(document.querySelectorAll(selector));
        } else if (selector instanceof Element) {
            this.elements = [selector];
        } else {
            this.elements = [];
        }
    }

    // 获取父级元素
    parent(selector) {
        const parents = this.elements.map(el => {
            let parent = el.parentElement;
            while (parent) {
                if (!selector || parent.matches(selector)) {
                    return parent;
                }
                parent = parent.parentElement;
            }
            return null;
        }).filter(Boolean);
        return new MQuery(parents[0]);
    }

    // 获取子元素
    children(selector) {
        const children = this.elements.flatMap(el => {
            // 使用querySelectorAll获取所有后代元素
            const allChildren = selector ?
                Array.from(el.querySelectorAll(selector)) :
                Array.from(el.children);
            return allChildren;
        });
        return new MQuery(children[0]);
    }

    // 获取兄弟元素
    siblings(selector) {
        const siblings = this.elements.flatMap(el => {
            const parent = el.parentElement;
            if (!parent) return [];
            const allSiblings = Array.from(parent.children).filter(child => child !== el);
            if (selector) {
                return allSiblings.filter(sibling => sibling.matches(selector));
            }
            return allSiblings;
        });
        return new MQuery(siblings[0]);
    }

    // 添加类
    addClass(className) {
        this.elements.forEach(el => {
            if (Array.isArray(className)) {
                el.classList.add(...className);
            } else {
                el.classList.add(className);
            }
        });
        return this;
    }

    // 移除类
    removeClass(className) {
        this.elements.forEach(el => {
            if (Array.isArray(className)) {
                el.classList.remove(...className);
            } else {
                el.classList.remove(className);
            }
        });
        return this;
    }

    // 切换类
    toggleClass(className) {
        this.elements.forEach(el => el.classList.toggle(className));
        return this;
    }

    // 设置或获取样式
    css(prop, value) {
        // 如果只传入一个参数且为对象,则批量设置样式
        if (typeof prop === 'object') {
            this.elements.forEach(el => {
                for (let key in prop) {
                    el.style[key] = prop[key];
                }
            });
            return this;
        }

        // 获取样式
        if (value === undefined) {
            return this.elements[0]?.style[prop];
        }

        // 设置单个样式
        this.elements.forEach(el => el.style[prop] = value);
        return this;
    }

    // 设置或获取属性
    attr(name, value) {
        if (value === undefined) {
            return this.elements[0]?.getAttribute(name);
        }
        this.elements.forEach(el => el.setAttribute(name, value));
        return this;
    }
    // 删除属性
    removeAttr(name) {
        this.elements.forEach(el => el.removeAttribute(name));
        return this;
    }

    // 设置或获取表单属性
    prop(name, value) {
        if (value === undefined) {
            return this.elements[0]?.[name];
        }
        this.elements.forEach(el => el[name] = value);
        return this;
    }

    // 设置或获取表单值
    val(value) {
        if (value === undefined) {
            return this.elements[0]?.value;
        }
        this.elements.forEach(el => el.value = value);
        return this;
    }

    // 设置或获取HTML内容
    html(content) {
        if (content === undefined) {
            return this.elements[0]?.innerHTML;
        }
        this.elements.forEach(el => el.innerHTML = content);
        return this;
    }

    // 设置或获取文本内容
    text(content) {
        if (content === undefined) {
            return this.elements[0]?.textContent;
        }
        this.elements.forEach(el => el.textContent = content);
        return this;
    }

    // 事件代理函数
    delegate(eventType, selector, handler) {
        if (!selector || !handler) {
            return this;
        }

        this.elements.forEach(el => {
            const wrapper = (e) => {
                const target = e.target;
                const matchedElement = target.matches(selector) ? target : target.closest(selector);
                if (matchedElement) {
                    handler.call(matchedElement, e);
                }
            };

            // 初始化事件存储
            if (!el._mquery_events) el._mquery_events = {};
            if (!el._mquery_events[eventType]) el._mquery_events[eventType] = [];

            // 存储事件处理函数和包装函数的映射关系
            el._mquery_events[eventType].push({ handler, wrapper });

            // 绑定事件
            el.addEventListener(eventType, wrapper);
        });

        return this;
    }

    // 事件绑定
    on(eventType, handler) {
        this.elements.forEach(el => {
            // 创建事件包装函数,保持正确的this指向
            const wrapper = (e) => handler.call(el, e);

            // 初始化事件存储
            if (!el._mquery_events) el._mquery_events = {};
            if (!el._mquery_events[eventType]) el._mquery_events[eventType] = [];

            // 存储事件处理函数和包装函数的映射关系
            el._mquery_events[eventType].push({ handler, wrapper });

            // 绑定事件
            el.addEventListener(eventType, wrapper);
        });
        return this;
    }

    // 移除事件
    off(eventType, handler) {
        this.elements.forEach(el => {
            if (!el._mquery_events || !el._mquery_events[eventType]) return;

            if (handler) {
                // 移除特定的事件处理函数
                const eventObj = el._mquery_events[eventType].find(e => e.handler === handler);
                if (eventObj) {
                    el.removeEventListener(eventType, eventObj.wrapper);
                    el._mquery_events[eventType] = el._mquery_events[eventType].filter(e => e.handler !== handler);
                }
            } else {
                // 移除该类型的所有事件
                el._mquery_events[eventType].forEach(eventObj => {
                    el.removeEventListener(eventType, eventObj.wrapper);
                });
                delete el._mquery_events[eventType];
            }
        });
        return this;
    }

    // 一次性事件绑定
    once(eventType, handler) {
        const wrapper = (e) => {
            handler.call(this, e);
            this.off(eventType, wrapper);
        };
        return this.on(eventType, wrapper);
    }

    // 触发事件
    trigger(eventType, data) {
        const event = new CustomEvent(eventType, {
            bubbles: true,
            cancelable: true,
            detail: data
        });

        this.elements.forEach(el => el.dispatchEvent(event));
        return this;
    }
}

// 创建一个工厂函数，类似于 jQuery 的 $
function $(selector) {
    return new MQuery(selector);
}

export default $;